<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组</title>
</head>
<body>
    <h1>数组</h1>

    <script>
        // 使用扩展运算符复制数组
        // bad
        const len = items.length;
        const itemsCopy = [];
        let i;
        for (i = 0; i < len; i++) {
            itemsCopy[i] = items[i];
        }

        // good
        const itemsCopy = [...items];

        // 使用Array.from转换类数组对象
        // bad
        const args = Array.prototype.slice.call(arguments);

        // good
        const args = Array.from(arguments);

        // 使用Array.from而不是扩展运算符...将类数组对象转换成数组
        const foo = document.querySelectorAll('.foo');
        
        // bad
        const nodes = [...foo];
        
        // good
        const nodes = Array.from(foo);

        // 实际应用示例
        // 数组去重
        function unique(array) {
            return Array.from(new Set(array));
        }

        // 数组映射
        const numbers = [1, 2, 3, 4];
        const doubled = numbers.map(num => num * 2);

        // 数组过滤
        const filtered = numbers.filter(num => num > 2);

        // 数组归约
        const sum = numbers.reduce((acc, curr) => acc + curr, 0);

        // 数组排序
        const users = [
            { name: '张三', age: 20 },
            { name: '李四', age: 18 },
            { name: '王五', age: 22 }
        ];

        // 按年龄排序
        users.sort((a, b) => a.age - b.age);

        // 数组分组
        function groupBy(array, key) {
            return array.reduce((result, item) => {
                (result[item[key]] = result[item[key]] || []).push(item);
                return result;
            }, {});
        }

        const groupedUsers = groupBy(users, 'age');
    </script>
</body>
</html> 